package com.sie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sie.entity.Authority;
import com.sie.entity.Role;
import com.sie.mapper.RoleMapper;
import com.sie.service.AuthorityService;
import com.sie.service.RoleService;
import com.sie.util.AsdUtils;
import com.sie.util.ReslUtil;
import com.sie.util.RoleAuthorityFormatUtils;
import com.sie.util.StatusUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 角色服务实现类
 */
@Service
@SuppressWarnings("all")
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl implements RoleService {
    @Autowired
    private AuthorityService authorityService;
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 查询所有角色
     *
     * @param request
     * @return
     */
    @Override
    public Map findAll(HttpServletRequest request) {
//        验证权限
        if (!AsdUtils.asd(request, "查询角色")) {
            return ReslUtil.fail();
        }
        Map success = ReslUtil.success();
//        查询所有角色
        List<Role> roles = roleMapper.selectList(new QueryWrapper<>());
//        排除超级管理员
        roles.remove(0);
        success.put("data", RoleAuthorityFormatUtils.roleFormat(roles));
        return success;
    }

    /**
     * 分页条件查询
     *
     * @param role
     * @param page
     * @param size
     * @param request
     * @return
     */
    @Override
    public Map findByPage(Role role, String page, String size, HttpServletRequest request) {
        if (!AsdUtils.asd(request, "查询角色")) {
            return ReslUtil.fail();
        }
        //        分页参数处理
        int pageNum, pageSize;
        try {
            pageNum = Integer.parseInt(page);
            pageSize = Integer.parseInt(size);
        } catch (Exception e) {
            pageNum = 1;
            pageSize = 5;
        }
//        分页查询
        PageHelper.startPage(pageNum, pageSize);
        if (role.getRoleName() != null && role.getRoleName().equals("")) {
            role.setRoleName("ROLE_" + role.getRoleName());
        }
        List<Role> roles = RoleAuthorityFormatUtils.roleFormat(roleMapper.findByPage(role));
        PageInfo<Role> rolePageInfo = new PageInfo<>(roles);
        roles.forEach(r -> {
            String roleStatus = r.getRoleStatus();
            if (StatusUtil.onTime(LocalDateTime.now().toString(), r.getOnTime()) && StatusUtil.offTime(LocalDateTime.now().toString(), r.getOffTime())) {
                if (roleStatus.equals("0")) {
                    r.setRoleStatus("1");
                    updateRole(request, r);
                    r.setRoleName(r.getRoleName().split("_")[1]);
                }
            } else {
                if (roleStatus.equals("1")) {
                    r.setRoleStatus("0");
                    updateRole(request, r);
                    r.setRoleName(r.getRoleName().split("_")[1]);
                }
            }
        });
//        获取所有有效 权限
        ArrayList<Authority> validAuth = new ArrayList<>();
        rolePageInfo.getList().forEach(item -> {
            validAuth.clear();
            for (Authority authority : authorityService.findAuthByRoleId(item.getRoleId() + "")) {
                if (authority.getAuthStatus().equals("1") && authority.getAuthLv().equals("3")) {
                    validAuth.add(authority);
                }
            }
            item.setAuthorities((List<Authority>) validAuth.clone());
        });
        Map success = ReslUtil.success();
        success.put("data", rolePageInfo.getList());
        success.put("total", rolePageInfo.getTotal());
        success.put("PageSize", rolePageInfo.getPageSize());
        return success;
    }

    /**
     * 新增角色
     *
     * @param request
     * @param role
     * @return
     */
    @Override
    public Map addRole(HttpServletRequest request, Role role) {
//        验证权限
        if (AsdUtils.asd(request, "新增角色") && role != null) {
//            拼接角色名约定
            role.setRoleName("ROLE_" + role.getRoleName());
//            获取合法时间
            if (role.getOnTime() == null || role.getOnTime().equals("")) {
                role.setOnTime(LocalDateTime.now().toString().split("T")[0]);
            }
            if (role.getOffTime() == null || "".equals(role.getOffTime()))
                role.setOffTime("9999-12-31");
//            插入操作
            int insert = roleMapper.insert(role);
            if (insert == 1) {
                return ReslUtil.success();
            }
        }
        return ReslUtil.fail();
    }

    /**
     * 修改角色
     *
     * @param request
     * @param role
     * @return
     */
    @Override
    public Map updateRole(HttpServletRequest request, Role role) {
        Integer integer = 0;
        if (role == null) {
            return ReslUtil.fail();
        }
//        判断权限
        if (AsdUtils.asd(request, "修改角色")) {
//            获取有效时间
            if (!(role.getOffTime() == null || role.getOnTime().equals("") || role.getOffTime() == null || role.getOffTime().equals(""))) {
                if (role.getOnTime().compareTo(role.getOffTime()) > 0) {
                    String temp = role.getOnTime();
                    role.setOnTime(role.getOffTime());
                    role.setOffTime(temp);
                }
            }
            String sysDate = LocalDateTime.now().toString();
            role.setRoleName("ROLE_" + role.getRoleName());
            String roleStatus = role.getRoleStatus();
//            根据状态修改时间
            if (roleStatus.equals("1")) {
                if (role.getOnTime() == null || role.getOnTime().equals("") || !StatusUtil.onTime(sysDate, role.getOnTime())) {
                    role.setOnTime(sysDate.split("T")[0]);
                }
                if (role.getOffTime() == null || role.getOffTime().equals("") || !StatusUtil.offTime(sysDate, role.getOffTime())) {
                    String t = sysDate.split("T")[0];
                    String[] split = t.split("-");
                    role.setOffTime((Integer.parseInt(split[0]) + 1) + "-" + split[1] + "-" + split[2]);
                }
            } else {
//                设置失效时间
                role.setOnTime("9999-99-99");
                role.setOffTime("9999-99-99");
            }
//            插入操作
            integer = roleMapper.updateRole(role);
        }
        if (integer == 1) {
            return ReslUtil.success();
        }
        return ReslUtil.fail();
    }

    /**
     * 角色名查重
     *
     * @param name
     * @return
     */
    @Override
    public Map findByName(String name) {
        if (name != null && !name.equals("")) {
            List<Role> byName = roleMapper.findByName("ROLE_" + name);
            if (byName.size() != 0) {
                return ReslUtil.fail();
            }
        }
        return ReslUtil.success();
    }

    /**
     * 查询编号是否存在
     *
     * @param no
     * @return
     */
    @Override
    public Boolean findByNo(String no) {
        Role byName = roleMapper.findByNo(no);
        if (byName == null) {
            return true;
        }
        return false;
    }

    /**
     * 设置角色
     *
     * @param empId
     * @param roleIdList
     * @return
     */
    @Override
    public Map setRole(HttpServletRequest request, String empId, List<String> roleIdList) {
        if (!AsdUtils.asd(request, "修改用户")) {
            return ReslUtil.fail();
        }
        try {
            if (empId == null || empId.equals(""))
                return ReslUtil.fail();
//            清空该用户所有角色
            roleMapper.offRolesByRoleId(empId);
            roleIdList.remove("1");
            roleIdList.forEach(id -> {
//                添加角色
                roleMapper.setRole(empId, id);
            });
            return ReslUtil.success();
        } catch (Exception e) {
            System.out.println("角色设置异常");
            throw e;
        }
    }

    /**
     * 获取合法编号
     *
     * @return
     */
    @Override
    public Map getNo() {
        String no = "";
        for (int i = 0; i < 6; i++) {
            no = no + RandomUtil.randomInt(0, 10);
        }
        if (!findByNo(no)) {
            getNo();
        }
        Map success = ReslUtil.success();
        success.put("no", no);
        return success;

    }

    /**
     * 根据id删除角色
     *
     * @param id
     * @param request
     * @return
     */
    @Override
    public Map deleteRoleById(String id, HttpServletRequest request) {
//        判断权限记忆排除超级管理员角色
        if (!AsdUtils.asd(request, "删除角色") || "1".equals(id)) {
            return ReslUtil.fail();
        }
//        删除所有角色信息
        Integer integer = roleMapper.deleteRole(id);
        roleMapper.deleteRoleAndEmp(id);
        roleMapper.deleteRoleAndAuthority(id);
        if (integer == 1)
            return ReslUtil.success();
        return ReslUtil.fail();
    }

    /**
     * 根据id批量删除角色
     *
     * @param list
     * @param request
     * @return
     */
    @Override
    public Map deleteRoleById(List<String> list, HttpServletRequest request) {
        if (!AsdUtils.asd(request, "删除角色")) {
            return ReslUtil.fail();
        }
//        排除超级管理员角色
        list.remove("1");
        roleMapper.deleteBatchIds(list);
//        list.forEach(e -> {
//            roleMapper.deleteRole(e);
//        });
        return ReslUtil.success();
    }


}
